/* Camera Example

    This example code is in the Public Domain (or CC0 licensed, at your option.)
    Unless required by applicable law or agreed to in writing, this
    software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
    CONDITIONS OF ANY KIND, either express or implied.
*/
#include <stdio.h>
#include <stdint.h>
#include <stddef.h>
#include <string.h>
#include "esp_wifi.h"
#include "esp_system.h"
#include "nvs_flash.h"
#include "esp_event.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/event_groups.h"
#include "esp_system.h"
#include "esp_heap_caps.h"
#include "esp_log.h"
#include "esp_spiffs.h"
#include "scan.h"
#include "button.h"
#include "page.h"
#include "smart_config.h"
#include "esp_event.h"
#include "driver/rmt.h"
#include "client.h"
#include "lvgl.h"
#include "mainPage.h"
#include "music.h"
// #include "esp_camera.h"


static const char *TAG = "main";

/**
 * @brief rgb -> rgb565
 *
 * @param r red   (0~31)
 * @param g green (0~63)
 * @param b red   (0~31)
 *
 * @return data about color565
 */
static unsigned int tick = 0;
void btn_smart_config_start()
{
    if (tick == 0)
    {
        smartconfig_wifi();
        tick = 1;
    }
}
void btn_smart_config(void *p)
{

    if (wait_key_value(&keyValue, 0) == pdTRUE)
    {
        
        if (keyValue == 6)
        {
            page_show_pre();
        }
        else if(keyValue == 7)
        {
            show_smart_config_wait();
        }
    }
    if (tick != 0)
    {
        if (wait_smart_config(0) == pdTRUE)
        {
            show_smart_config_ok();
            tick = 0;
        }
        else
        {
            tick++;
            if (tick >= 600)
            {
                show_smart_config_fail();
                smart_config_end();
                tick = 0;
            }
        }

    }
}

void app_main()
{
    /*< RGB display */
    esp_err_t ret = nvs_flash_init();
    if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND)
    {
        ESP_ERROR_CHECK(nvs_flash_erase());
        ret = nvs_flash_init();
    }
    ESP_ERROR_CHECK(ret);

    // wifiScanQueue = xQueueCreate(1, sizeof(int));

    ESP_ERROR_CHECK(esp_netif_init());
    ESP_ERROR_CHECK(esp_event_loop_create_default());
    esp_netif_t *sta_netif = esp_netif_create_default_wifi_sta();
    assert(sta_netif);
    wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
    ESP_ERROR_CHECK(esp_wifi_init(&cfg));
    ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA));
    ESP_ERROR_CHECK(esp_wifi_start());

    page_init();

    button_init();

    esp_wifi_connect();
    client_init();
    music_init();
    lv_timer_create(&btn_smart_config, 100, 0);


    while (1)
    {
        lv_thread();
    }
}
